package com.pathpad.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.pathpad.dao.WebappDao;
import com.pathpad.hibernate.PPUser;
import com.pathpad.hibernate.PPUserCommonPad;

public class LoginController implements Controller {

	/*
	 * private HelloManager helloManager;
	 * 
	 * public void setHelloManager(HelloManager helloManager) {
	 * this.helloManager = helloManager; }
	 */

	private WebappDao webappDao;

	@Transactional
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (null == request.getParameter("userName")
				|| "".equals(request.getParameter("userName"))
				|| null == request.getParameter("password")
				|| "".equals(request.getParameter("password"))) {

			request.setAttribute("message", "用户名或密码不能够为空！！！ ");
			return new ModelAndView("index");
		}
		List<PPUser> resultList = null;
		System.out.println(webappDao);
		try {
			resultList = webappDao.findNotSendTargetEntity(PPUser.class,
					request.getParameter("userName"));
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("hello_1",
					"失败！！！ " + request.getParameter("userName"));
			return new ModelAndView("login");
			// TODO: handle exception
		}

		if (null == resultList || resultList.size() == 0) {
			PPUser ppUser = new PPUser();
			ppUser.setUserId(request.getParameter("userName"));
			ppUser.setEmail("jiangzhen@pp.com");
			ppUser.setPassword(request.getParameter("password"));
			webappDao.savePPUserTableVaule(ppUser);
			request.setAttribute("hello_1",
					"注册成功！ " + request.getParameter("userName"));
			// request.setAttribute("hello_1", "用户名或密码错误！！！ ");
			request.getSession().setAttribute("userInfo", ppUser);
			return new ModelAndView("login");
		}
		if (resultList.get(0).getPassword()
				.equals(request.getParameter("password"))) {
			request.getSession().setAttribute("userInfo", resultList.get(0));
			request.setAttribute("hello_1", request.getParameter("userName")
					+ "， 欢迎回来！ <br>" + resultList.get(0).getEmail());
			List<PPUserCommonPad> resultPPUserCommonPadList = webappDao
					.findPPUserCommonPad(resultList.get(0).getUserId());

			if (null != resultPPUserCommonPadList
					&& resultPPUserCommonPadList.size() != 0) {
				request.setAttribute("indexWebsitesList", resultPPUserCommonPadList);
			}
			return new ModelAndView("login");
		} else {
			request.setAttribute("message", "用户名或密码错误！！！");
			return new ModelAndView("index");
		}
	}

	public WebappDao getWebappDao() {
		return webappDao;
	}

	public void setWebappDao(WebappDao webappDao) {
		this.webappDao = webappDao;
	}

}
